<template>
  <div class="mui-content mh-containe pd">
    <mh-header headName="消息" :showBack="showBack"> </mh-header>
    <div class="mui-segmented-control mh-segmented sub-control">
      <a class="mui-control-item mui-active" href="javascript:" @click='getData(1)'>全部
        <!-- <span class="mui-badge mui-badge-danger unread">5</span> -->
      </a>
      <a class="mui-control-item" href="javascript:" @click='getData(2)'>红娘</a>
      <a class="mui-control-item" href="javascript:" @click='getData(3)'>相亲</a>
      <a class="mui-control-item" href="javascript:" @click='getData(4)'>购物</a>
      <a class="mui-control-item" href="javascript:" @click='getData(5)'>备注</a>
    </div>
    <div class="msg-list">
      <div class="msg-item flex-bt" @tap="toMsg(1,'客服小M', 1)">
        <div class="msg-info flex">
          <img class="msg-avatar" src="../../assets/images/demo/kefu.jpg" alt="">
          <div>
            <p class="mui-ellipsis msg-name">客服小M</p>
            <p class="mui-ellipsis">在线客服咨询</p>
          </div>
        </div>
      </div>
      <div class="msg-item flex-bt" v-for="item in msgList" :key="item.id" @tap="toMsg(item.msgType,item.name, item.id)" v-if='item.msgType==type'>
        <div class="msg-info flex">
          <img class="msg-avatar" :src="item.ico" alt="">
          <div>
            <p class="mui-ellipsis msg-name" v-text="item.name">-</p>
            <p class="mui-ellipsis" v-text="item.content">-</p>
          </div>
        </div>
        <div class="msg-sub-info mui-text-right" v-if="item.msgType === 1">
          <p class="msg-time" v-text="item.time">0:00</p>
          <p>
            <!-- <span class="mui-badge mui-badge-danger">5</span> -->
          </p>
        </div>
        <div class="msg-sub-info mui-text-right" v-if="item.msgType === 2">
          <span class="adv-badge">广告</span>
        </div>
        <div class="msg-sub-info mui-text-right" v-if="item.msgType === 3">
          <p class="msg-time" v-text="item.time">0:00</p>
        </div>
      </div>
      <div class="msg-item flex-bt" v-for="(item, index) in annoArr" :key="item.id" @tap="viewAnno(index)">
        <div class="msg-info flex">
          <img class="msg-avatar" :src="item.logo" alt="">
          <div>
            <p class="mui-ellipsis msg-name">{{item.name}}</p>
            <p class="mui-ellipsis anno-info">{{item.introduce}}</p>
          </div>
        </div>
        <div class="msg-sub-info mui-text-right">
          <span class="adv-badge">广告</span>
        </div>
      </div>
    </div>
    <tab-menu :activeTab="activeFootTab"> </tab-menu>
  </div>
</template>

<script>
  import MhHeader from '@/components/mh-header/mh-header'
  import TabMenu from '@/components/tab-menu/tab-menu';
  import {MH_API} from "@/api/api";
  export default {
    name: "explore",
    data () {
      return {
        activeFootTab: 2,
        showBack: false,
        msgList: [
          // {
          //   id: '1',
          //   name: '聊天测试',
          //   time: '15:30',
          //   content: '123',
          //   msgs: 5,
          //   msgType: 1,
          //   ico: 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132'
          // },
        ],
        rongyun: {},
        type: 1,
        annoArr: []
      }
    },
    methods: {
      getDange(){
        MH_API.getSensitive({

        }).then(res => {
          if (res.status == 200) {

          }
        })
      },
      viewAnno(index){
        this.$router.push({
          path: '/annoView',
          query: {
            index: index
          }
        })
      },
      toMsg (type, name, id) {
        if (type === 1) {
          this.$router.push({
            path: '/chat',
            query: {
              name: name,
              id: id
            }
          })
        }
      },
      getData(type){
        this.type = type;
      },
      //获取用户信息
      getUser(id){
        let obj = {};
        MH_API.getMember({
          user_id: id
        }).then(res => {
          if (res.status === 200) {
            obj.ico = res.data.portrait;
            obj.name = res.data.nickname;
          }
        })
        return obj
      }
    },
    components: {
      MhHeader,
      TabMenu
    },
    mounted(){
      let self = this;


    },
    created(){
      this.getData(1);
      //this.getDange();
      let self = this;
      let targetId = this.$route.query.id;
      //聊天列表
      let rongyun = JSON.parse(window.localStorage.getItem("rongyun"));
      console.log(rongyun)
      let token = rongyun.token;
      let userId = rongyun.id;
      RongIMLib.RongIMClient.init("sfci50a7s3qxi");
      // 设置连接监听状态 （ status 标识当前连接状态 ）
       // 连接状态监听器
       RongIMClient.setConnectionStatusListener({
          onChanged: function (status) {
              switch (status) {
                  case RongIMLib.ConnectionStatus.CONNECTED:
                      console.log('链接成功');
                      break;
                  case RongIMLib.ConnectionStatus.CONNECTING:
                      console.log('正在链接');
                      break;
                  case RongIMLib.ConnectionStatus.DISCONNECTED:
                      console.log('断开连接');
                      break;
                  case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                      console.log('其他设备登录');
                      break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                      console.log('域名不正确');
                      break;
                  case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                    console.log('网络不可用');
                    break;
                  }
          }});

       // 消息监听器
       RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: function (message) {
              console.log(message)
              // 判断消息类型
              switch(message.messageType){
                  case RongIMClient.MessageType.TextMessage:
                      // message.content.content => 消息内容
                      if(message.content.content){
                        console.log("收到的消息："+message.content.content)
                          // var temp = '<div class="mes-box your"><div class="logo"><img src="'+yourLogo+'"></div><div class="con"><em></em>'+message.content.content+'</div></div>'
                          // $("#rcs-app").append(temp);
                      }
                      break;
                  case RongIMClient.MessageType.VoiceMessage:
                      // 对声音进行预加载                
                      // message.content.content 格式为 AMR 格式的 base64 码
                      break;
                  case RongIMClient.MessageType.ImageMessage:
                     // message.content.content => 图片缩略图 base64。
                     // message.content.imageUri => 原图 URL。
                     break;
                  case RongIMClient.MessageType.DiscussionNotificationMessage:
                     // message.content.extension => 讨论组中的人员。
                     break;
                  case RongIMClient.MessageType.LocationMessage:
                     // message.content.latiude => 纬度。
                     // message.content.longitude => 经度。
                     // message.content.content => 位置图片 base64。
                     break;
                  case RongIMClient.MessageType.RichContentMessage:
                     // message.content.content => 文本消息内容。
                     // message.content.imageUri => 图片 base64。
                     // message.content.url => 原图 URL。
                     break;
                  case RongIMClient.MessageType.InformationNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ContactNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ProfileNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.UnknownMessage:
                      // do something...
                     break;
                  default:
                      // do something...
              }
          }
      });

      //链接服务器
      RongIMClient.connect(token, {
          onSuccess: function(userId) {
            console.log("Connect successfully." + userId);
          },
          onTokenIncorrect: function() {
            console.log('token无效');
          },
          onError:function(errorCode){
                var info = '';
                switch (errorCode) {
                  case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                  case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                  case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                  case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
                }
                console.log(errorCode);
              }
        });

      //设置重连
      var callback = {
          onSuccess: function(userId) {
              console.log("Reconnect successfully." + userId);
          },
          onTokenIncorrect: function() {
              console.log('token无效');
          },
          onError:function(errorCode){
              console.log(errorcode);
          }
      };
      var config = {
          // 默认 false, true 启用自动重连，启用则为必选参数
          auto: true,
          // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
          url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
          // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
          rate: [100, 1000, 3000, 6000, 10000]
      };
      RongIMClient.reconnect(callback, config);
      function add0(m){return m<10?'0'+m:m }
      function format(shijianchuo)
      {
        //shijianchuo是整数，否则要parseInt转换
        var time = new Date(shijianchuo);
        var y = time.getFullYear();
        var m = time.getMonth()+1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        //return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
        return add0(h)+':'+add0(mm);
      }
      setTimeout(function(){
        //会话列表
        RongIMClient.getInstance().getConversationList({
            onSuccess: function(list) {
                // list => 会话列表集合
                console.log(list)
                let msgList = [];
                for(let i=0,len=list.length;i<len;i++){
                  var time = list[i].sentTime;
                  let obj = self.getUser(list[i].targetId);
                  setTimeout(function(){
                    msgList.push({
                      id: list[i].targetId,
                      name: obj.name || list[i].targetId,
                      time: format(time),
                      content: list[i].latestMessage.content.content,
                      msgType: 1,
                      ico: obj.ico || 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJKpp1HCnDWb1TI4zG7mvIYoHjotHJGdTM7dpkACGfueIfQYIBvnCFHQqLca7l3HFHUQCbNARGqdA/132'
                    })
                  }, 300)
                }
                self.msgList = msgList;
            },
            onError: function(error) {
                // do something
            }
        }, null);
      }, 500)

      //广告
      MH_API.getGuanggao({
        
      }).then(res => {
        if (res.status === 200) {
          let newArr = res.data;
          for(let i=0, len=newArr.length;i<len;i++){
            if(newArr[i].image && newArr[i].image.indexOf("hunlian/Uploads")!="-1"){
              newArr[i].logo = "http://yueqiutao.com" + newArr[i].image;
            }
          }
          self.annoArr = newArr
        }
      })
    }
  }
</script>

<style lang="scss" scoped>
  .mui-segmented-control {
    padding: 1rem 0;
    border-bottom: 1px solid #eee;
  }
  .mui-control-item.mui-active span {border-bottom: 0;}
  .unread {
    position: absolute;
    background: #f26c60;
    color: #fff;
    font-size: .9rem;
  }
  .msg-item {
    width: 100%;
    padding: 1rem;
    background-color: #fff;
    border-bottom: 1px solid #eeeeee;
  }
  .msg-avatar {
    width: 5rem;
    height: 5rem;
    margin-right: .8rem;
    border-radius: 100%;
  }
  .msg-name {
    margin-bottom: .5rem;
    font-size: 1.5rem;
    color: #333;
  }
  .msg-time {margin-bottom: .8rem}
  .adv-badge {
    font-size: .9rem;
    color: #2381fd;
    border: 1px solid #2381fd;
    padding: .1rem .3rem;
  }
  .anno-info{ width:25rem;}
</style>
